/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.lvyh.lightframe.sharding.client.util;

import com.alibaba.druid.sql.PagerUtils;
import com.alibaba.druid.util.JdbcConstants;
import org.apache.ibatis.cache.CacheKey;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;

import java.lang.reflect.Field;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class ExecutorUtil {

    private static Field additionalParametersField;

    static {
        try {
            additionalParametersField = BoundSql.class.getDeclaredField("additionalParameters");
            additionalParametersField.setAccessible(true);
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }
    }

    public static Long executeManualCount(Executor executor, MappedStatement countMs, Object parameter, BoundSql boundSql, ResultHandler resultHandler) throws Exception {
        CacheKey countKey = executor.createCacheKey(countMs, parameter, RowBounds.DEFAULT, boundSql);

        BoundSql countBoundSql = countMs.getBoundSql(parameter);
        Object countResultList = executor.query(countMs, parameter, RowBounds.DEFAULT, resultHandler, countKey, countBoundSql);
        Long count = ((Number) ((List) countResultList).get(0)).longValue();
        return count;
    }

    public static Long executeAutoCount(String sql, Executor executor, MappedStatement countMs, Object parameter, BoundSql boundSql, RowBounds rowBounds, ResultHandler resultHandler) throws Exception {

        CacheKey cacheKey = executor.createCacheKey(countMs, parameter, RowBounds.DEFAULT, boundSql);
        //销毁第一级缓存
        cacheKey.update(new Object());

        String newCountSql = getNewCountSql(sql);
        Map<String, Object> additionalParameters = getAdditionalParameter(boundSql);

        // 重新new一个查询语句对象
        BoundSql countBoundSql = new BoundSql(countMs.getConfiguration(), newCountSql, boundSql.getParameterMappings(), parameter);
        setAdditionalParameter(countBoundSql, additionalParameters);
        Object resultList = executor.query(countMs, parameter, RowBounds.DEFAULT, resultHandler, cacheKey, countBoundSql);

        Long count = (Long) ((List) resultList).get(0);
        return count;
    }


    public static String getNewCountSql(String sql) throws Exception {
        //count(0)=count(1)=count(*)
        String newCountSql = PagerUtils.count(sql, JdbcConstants.MYSQL);
        return newCountSql;
    }


    public static MappedStatement getExistedMappedStatement(Configuration configuration, String msId) {
        MappedStatement mappedStatement = null;
        try {
            mappedStatement = configuration.getMappedStatement(msId, false);
        } catch (Throwable t) {
        }
        return mappedStatement;
    }

    public static <E> List<E> query(String sql, Executor executor, MappedStatement ms, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql, CacheKey cacheKey) throws SQLException, IllegalAccessException {

        // 重新new一个查询语句对象
        BoundSql newBoundSql = new BoundSql(ms.getConfiguration(), sql, boundSql.getParameterMappings(), boundSql.getParameterObject());
        Map<String, Object> additionalParameters = getAdditionalParameter(boundSql);
        setAdditionalParameter(newBoundSql, additionalParameters);
        return executor.query(ms, boundSql.getParameterObject(), rowBounds, resultHandler, cacheKey, newBoundSql);

    }

    private static void setAdditionalParameter(BoundSql boundSql, Map<String, Object> additionalParameters) {
        Iterator var11 = additionalParameters.keySet().iterator();

        while (var11.hasNext()) {
            String key = (String) var11.next();
            boundSql.setAdditionalParameter(key, additionalParameters.get(key));
        }
    }

    public static Map<String, Object> getAdditionalParameter(BoundSql boundSql) throws IllegalAccessException {
        return (Map<String, Object>) additionalParametersField.get(boundSql);
    }
}
